#include "mainwindowimpl.h"
#include "decoratorquestionnairemodel.h"
#include "sd.h"
#include <QItemSelectionModel>
#include <QItemSelection>
#include <QFileDialog>
//
MainWindowImpl::MainWindowImpl( QWidget * parent, Qt::WFlags fl)
	: QMainWindow(parent, fl), m(new DecoratorQuestionnaireModel(this)){
	setupUi(this);
	treeView->setModel(m->model());

	connect(treeView->selectionModel(),
	        SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
					selectQuestionActn, SLOT(trigger()));
}
//

void MainWindowImpl::on_addQuestionActn_triggered(){
//	int n = m->model()->rowCount();
	m->addQuestion();
	treeView->resizeColumnToContents(0);
//	treeView->clearSelection();
//	treeView->selectionModel()->select(QItemSelection(m->model()->index(n,0), m->model()->index(n,1)),
//	                                   QItemSelectionModel::Select);
}

void MainWindowImpl::on_selectQuestionActn_triggered(){
	QModelIndex i = treeView->selectionModel()->selectedIndexes().at(0);
	if(i.parent() == QModelIndex())
		m->selectQuestion(i.row());
	else
		m->selectQuestion(i.parent().row());
}

void MainWindowImpl::on_addVariantActn_triggered(){
	m->addVariant();
	treeView->resizeColumnToContents(0);
}

void MainWindowImpl::on_openActn_triggered(){
	fileName = QFileDialog::getOpenFileName(this, trUtf8("Откройте файл анкеты."));
	m->open(fileName);
}

void MainWindowImpl::on_saveActn_triggered(){
	if (fileName.isEmpty())
		on_saveAsActn_triggered();
	else
		m->save(fileName);
}

void MainWindowImpl::on_saveAsActn_triggered(){
	fileName = QFileDialog::getSaveFileName(this, trUtf8("Куда сохранить файл анкеты?"));
	m->save(fileName);
}
